﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using SomeGame.GUI.Screens;

namespace SomeGame.GUI {

    public static class ScreenManager {

        private const string SCREEN_NAMESPACE = "SomeGame.GUI.Screens";
        // Screens.
        public const string BACKGROUND_SCREEN = "BackgroundScreen";
        public const string MAIN_MENU_SCREEN = "MainMenuScreen";
        public const string PLAY_SCREEN = "PlayScreen";
        public const string PAUSED_SCREEN = "PausedScreen";
        public const string ARE_YOU_SURE_SCREEN = "AreYouSureScreen";

        public static readonly RasterizerState NormalRasterizerState = new RasterizerState();
        public static readonly RasterizerState ScissorRasterizerState = new RasterizerState {
            ScissorTestEnable = true
        };
        private static readonly IList<Screen> ActiveScreens = new List<Screen>();

        public static void Update(GameTime gameTime) {
            for (int i = ActiveScreens.Count-1; i >= 0; i--) {
                ActiveScreens[i].Update(gameTime);
            }
        }

        public static void Draw() {
            for (int i = 0; i < ActiveScreens.Count; i++) {
                ActiveScreens[i].Draw();
            }
        }

        public static bool ScreenIsActive(string name) {
            return ActiveScreens.Any(x => x.Name == name);
        }

        public static void ActivateScreen(string name) {
            Type type = Type.GetType(SCREEN_NAMESPACE+"."+name);
            if (type == null) {
                return;
            }
            // Adding a new screen makes it the TopScreen, so flag all others off.
            for (int i = ActiveScreens.Count-1; i >= 0; i--) {
                ActiveScreens[i].IsTopScreen = false;
            }
            Screen newScreen = Activator.CreateInstance(type) as Screen;
            newScreen.IsTopScreen = true;
            ActiveScreens.Add(newScreen);
        }

        public static void DeactivateScreen(string name) {
            Screen targetScreen = ActiveScreens.SingleOrDefault(x => x.Name == name);
            if (targetScreen == null) {
                return;
            }
            ActiveScreens.Remove(targetScreen);
            // Screen may have been the top screen, so make sure a new top screen is set.
            Screen topScreen = ActiveScreens.LastOrDefault();
            if (topScreen != null) {
                topScreen.IsTopScreen = true;
            }
        }

        public static void DeactivateAllScreens() {
            for (int i = ActiveScreens.Count-1; i >= 0; i--) {
                DeactivateScreen(ActiveScreens[i].Name);
            }
        }

    }

}